package org.example.service.imp;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import lombok.extern.slf4j.Slf4j;
import org.example.mapper.EmpExprMapper;
import org.example.mapper.EmpMapper;
import org.example.pojo.*;
import org.example.service.EmpLogService;
import org.example.service.EmpService;
import org.example.utils.JwtUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Slf4j
@Service
public class EmpServiceImp implements EmpService {
    private final EmpMapper empMapper;
    private EmpMapper EmpMapper;
    //构造器注入
    public EmpServiceImp(EmpMapper empMapper) {
        this.EmpMapper = empMapper;
        this.empMapper = empMapper;
    }
    @Autowired
    private EmpLogService empLogService;
    @Autowired
    private EmpExprMapper empExprMapper;

    @Override//查询分页
    public PageResult<Emp> findByPage(EmpQueryParm empQueryParm) {
        //原始分页查询
//        Long total =EmpMapper.count();
//        List<Emp> rows = EmpMapper.findByPage((page-1)*pageSize,pageSize);
//        return new PageResult<Emp>(total,rows);
        //设置分页参数
        PageHelper.startPage(empQueryParm.getPage(),empQueryParm.getPageSize());
        //执行查询
        List<Emp> empList = EmpMapper.findAll(empQueryParm);
        //解析查询结果，并封装
        Page<Emp> p =(Page<Emp>)empList;
        return new PageResult<>(p.getTotal(), p.getResult());

    }
    @Transactional(rollbackFor = Exception.class )//事务控制
    @Override
    public void save(Emp emp) {
        try {
            //保存员工基本信息
            emp.setCreateTime(LocalDateTime.now());
            emp.setUpdateTime(LocalDateTime.now());
            empMapper.insert(emp);
            //保存员工工作经历
            List<EmpExpr> exprList = emp.getExprList();
            if(emp.getExprList() !=null){
                exprList.forEach(expr->{
                    expr.setEmpId(emp.getId());
                });
                empExprMapper.insert(exprList);
            }
        } finally {
            //记录操作日志
            empLogService.insert(new EmpLog(null,LocalDateTime.now(),"新增员工"+emp));
        }

    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public void delete(List<Integer> ids) {
        //删除员工基本信息
        EmpMapper.deleteByIds(ids);
        //删除员工工作经历
        empExprMapper.deleteByEmpIds(ids);
    }


    @Override
    public Emp findById(Integer id) {
        return  EmpMapper.findById(id);


    }
    //更新员工信息
    @Transactional(rollbackFor = Exception.class)
    @Override
    public void update(Emp emp) {
        emp.setUpdateTime(LocalDateTime.now());
        //更新员工基本信息
        empMapper.update(emp);
        //更新员工工作经历：删除原来的，再保存新的
        empExprMapper.deleteByEmpIds(Collections.singletonList(emp.getId()));//删除原来的
        if(emp.getExprList() !=null){
            emp.getExprList().forEach(expr->{
                expr.setEmpId(emp.getId());
            });
            empExprMapper.insert(emp.getExprList());
        }
    }

    @Override
    public List<Emp> findAll() {
        return empMapper.findAll(null);
    }

    public LoginInfo login(Emp emp) {
        //查询员工
       Emp e =  empMapper.selectByUsernameAndPassword(emp);
       //判断员工是否存在
        if(e != null){
            //生成token
            Map<String,Object>  claims = new HashMap<>();
            claims.put("id",e.getId());
            claims.put("userName",e.getUsername());
             String jwt = JwtUtils.generateToken(claims);
             log.info("登陆成功,员工信息{}",e);
            //返回登录信息
            return new LoginInfo(e.getId(),e.getUsername(),e.getName(),jwt);
        }
        return null;
    }


}
